<template>
  <form id="submitImgForm"
    method="post" 
    enctype="multipart/form-data" 
    :action="url">
    <label class="single-upload-wrap" :class="{disabled: disabled}" :style="{width: `${width}px`, height: `${height}px`, 'line-height': `${height}px`, 'font-size': `${width * .11}px`}">
      <span v-if="disabled">暂未上传图片</span>
      <span class="bg" v-else :class="{'cardup': bgimgtype == 'cardup', 'carddown': bgimgtype == 'carddown', 'licence': bgimgtype == 'licence'}">{{bgimgtype ? '' : '点击上传图片'}}</span>
      <input type="file" 
        name="imgFile"
        :disabled="disabled"
        @change="onChangeFile">
        <img v-lazy="imageSrc" v-show="imageSrc">
    </label>
    <input v-if="isType" type="hidden" name="type" :value="type">
  </form>
</template>

<script>
  export default {
    props: {
      imgsrc: [String], // 图片地址
      url: [String], // 图片上传URL地址
      width: {
        type: Number,
        default: 200
      },
      height: {
        type: Number,
        default: 100
      },
      disabled: {
        type: Boolean,
        default: false
      },
      bgimgtype: {
        type: String,
        default: ''
      },
      isType: [Boolean], // 判断是否需传type
      type: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        imageSrc: this.imgsrc
      }
    },
    methods: {
      // 选择图片
      onChangeFile(ev) {
        const imgVal = ev.target.value || ''
        if (!/.jpg|.jepg|.png/i.test(imgVal)) {
          this.$toast('图片格式无效，请重新选择')
          return
        }
        $('#submitImgForm').ajaxSubmit(data => {
          this.imageSrc = data.data.url
          this.$emit('on-upload', this.imageSrc)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .single-upload-wrap {
    position: relative;
    display: block;
    width: 100%;
    height: 100%;
    text-align: center;
    color: #999;
    border: 1px solid #ccc;
    cursor: pointer;
    &.disabled {
      cursor: not-allowed;
    }
    .bg {    
      width: 84px;
      height: 48px;
      display: inline-block;
      background-repeat: no-repeat;
      margin: 0 auto;
      vertical-align: middle;
      &.cardup {
        background-image: url(../../assets/icon_card_up.png)
      }
      &.carddown {
        background-image: url(../../assets/icon_card_down.png)
      }
      &.licence {
        background-image: url(../../assets/icon_licence.png)
      }
    }
    img {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }
    input {
      width: 0;
      height: 0;
      opacity: 0;
    }
  }
</style>